// pages/add_week/index.js
const app = getApp()
const root = app.globalData.url 
const rootimgurl=app.globalData.rootimgurl
import { chooseImage,uploadFile,showModal} from '../../utils/asyncwx.js'
const http = require('../../utils/http.js');
import regeneratorRuntime from '../../lib/runtime/runtime'
let util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: null,
    picker: [],//发射台数组
    index: 0, //选中的发射台数组序号
    dtype: null,
    uid: '',
    tname: '',
    role: null,  //是否有权限
    pdList:null,//发射机数组
    fsjId:0, //发射机编号  
    pdname:'', //发射机名称
    workFre:'',
    inPower:'',
    backPower:'',
    zhubo:'',
    ambV:'',
    ambA:'',
    mainSignal:true,
    backSignal:true,
    content:'',
    posttype:'添加',
    logid:'',
    totalnum:'',
    todonum:'',
    imgList: [],
    imgindex: 0,
  },
  async ChooseImage() {
    //图像选择
    let res=await chooseImage()
    
    if (this.data.imgList.length != 0) {
      // // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      this.setData({
        imgList: this.data.imgList.concat(res.tempFilePaths)
      })
    } else {
      this.setData({
        imgList: res.tempFilePaths
      })
    }
  },// end of ChooseImage
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  async DelImg(e) {
    let res=await showModal({content:'确定要删除这张图片吗？',showCancel:false}) 
    if (res.confirm) {
      this.data.imgList.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        imgList: this.data.imgList
      })
    }
  },// end of DelImg
  handle_work_fre(e) {
    //work_fre输入处理
    let value = e.detail.value
  
    this.setData({
      workFre: value
    })
  },
  handle_in_power(e) {
    //in_power输入处理
    let value = e.detail.value
  
    this.setData({
      inPower: value
    })
  },
  handle_back_power(e) {
    //back_power输入处理
    let value = e.detail.value
   
    this.setData({
      backPower: value
    })
  },
  handle_zhubo(e) {
    //back_power输入处理
    let value = e.detail.value
  
    this.setData({
      zhubo: value
    })
  },
  handle_amb_v(e) {
    //amb_v输入处理
    let value = e.detail.value
   
    this.setData({
      ambV: value
    })
  },
  handle_amb_a(e) {
    //amb_a输入处理
    let value = e.detail.value
   
    this.setData({
      ambA: value
    })
  },
  listenerSwitchm: function (e) {
   
    this.setData({
      mainSignal: e.detail.value
    })

  },
  listenerSwitchb: function (e) {
   
    this.setData({
      backSignal: e.detail.value
    })

  },
  textareaBInput(e) {
    //内容输入处理
    const value = e.detail.value
    this.setData({
      content: value
    })


  },
  async dosubmit() {
    //提交数据
    let date=this.data.date
    let workFre = this.data.workFre
    let inPower = this.data.inPower
    let backPower = this.data.backPower
    let zhubo = this.data.zhubo
    let ambV = this.data.ambV
    let ambA = this.data.ambA
    let content = this.data.content
    let uid = this.data.uid
    let fsjId = this.data.fsjId
    let mainSignal = this.data.mainSignal
    let backSignal = this.data.backSignal
    let pdname=this.data.pdname
    let title=date//+" "+ pdname
    let posttype = this.data.posttype
    let logid=this.data.logid
    wx.showLoading({
      title: '正在创建...',
      mask: true
    })
    
    let url = 'fsjData/add';
    if (posttype=='修改'){
      url = 'fsjData/edit';
    }
    let arr = []
    
    //判断是否需要上传图片
    if (this.data.imgList[0].indexOf(rootimgurl) >= 0) {

     
    
        // 上传成功，获取这些图片在服务器上的地址，组成一个数组

      let imgs = this.data.imgList[0]
        // let uvideo = res.map(item => JSON.parse(item.data).url)
        let data = {
          title: title,
          workFre: workFre,
          inPower: inPower,
          backPower: backPower,
          zhubo: zhubo,
          ambV: ambV,
          ambA: ambA,
          content: content,
          fsjId: fsjId,
          mainSignal: mainSignal,
          backSignal: backSignal,
          uid: uid,
          posttype: posttype,
          logid: logid,
          imgs: imgs

        }
        let res= await http.post(url,data)
      
          if (res == 'ok') {
           
            this.get_log_dat()
            wx.showToast({
              title: '提交成功',
              icon: 'succes',
              duration: 1000,
              mask: true
            })
          }
        
        wx.hideLoading()

    }else{
      //不包含
      try {
       
      for (let path of this.data.imgList) {
        let res=await uploadFile(
          root+'file/uploadPic',
          path,
          'uploadimg',
          {}
         )
  
        //console.log('图片地址',JSON.parse(res.data))
       
        arr.push(JSON.parse(res.data).data.imgurl)
      }
     // let imgs = res.map(item => JSON.parse(item.data).url)
      // let uvideo = res.map(item => JSON.parse(item.data).url)

      let data = {
        title: title,
        workFre: workFre,
        inPower: inPower,
        backPower: backPower,
        zhubo: zhubo,
        ambV: ambV,
        ambA: ambA,
        content: content,
        fsjId: fsjId,
        mainSignal: mainSignal,
        backSignal: backSignal,
        uid: uid,
        posttype: posttype,
        logid: logid,
        imgs: arr

      }
      let res= await http.post(url,data)
    
        if (res == 'ok') {
      
          this.get_log_dat()
          wx.showToast({
            title: '提交成功',
            icon: 'succes',
            duration: 1000,
            mask: true
          })
        }
      
    }catch (error) {
      showModal({content:'上传错误!'+error,showCancel:false})
    }
    }
    
    //wx.switchTab({
    //  url: '../../pages/all_week/index'
    //})
  },
  async submitForm(e) {

  
    let workFre = this.data.workFre
    let inPower = this.data.inPower
    let ambV = this.data.ambV
    let ambA = this.data.ambA

    if (this.data.hasrole == "0") {
      await showModal({content:'信息不全，请先完善您的个人信息!',showCancel:false})
      wx.switchTab({
        url: '/pages/mine/index'
      })
      return false;
    }



    if (workFre && inPower && ambV && ambA) {
      this.dosubmit()

    } else {
    
      await showModal({content:'请输入所有*号必填项目!',showCancel:false})
 
    }
  },
  Steps(e) {
    //频道选择切换
    let id = e.currentTarget.dataset.id.id
    let pdname = e.currentTarget.dataset.id.fst_pd
   
   
    this.setData({
      fsjId: id,
      pdname: pdname
    })
  
    this.get_log_dat() //调取当日 对应频道数据
    
  },

  async get_log_dat(){
    //获取频道发射机对应日期数据
   
   
    let url = 'fsjData/detail';
    let data = {
      fsjId: this.data.fsjId,
      title: this.data.date,
      fstId: this.data.dtype
    }
    let res= await http.post(url,data)
  
    if (res.fsjData.length===0){
       
      this.setData({
        workFre: "",
        inPower: "",
        backPower: "",
        zhubo: "",
        ambV: "",
        ambA: "",
        content: "",
        imgList:[],
        mainSignal: true,
        backSignal: true,
        posttype:'添加',
        logid:''
      });  
    }else
    {
     
      this.setData({
        workFre: res.fsjData[0].workFre,
        inPower: res.fsjData[0].inPower,
        backPower: res.fsjData[0].backPower,
      zhubo: res.fsjData[0].zhubo,
      ambV: res.fsjData[0].ambV,
      ambA: res.fsjData[0].ambA,
      content: res.fsjData[0].content,
      logid: res.fsjData[0].id,
     //  imgList: res.result[0].imgs,
      posttype:'修改'
     // main_signal: res.result[0].main_signal,
     // back_signal: res.result[0].back_signal,
     }); 
     //处理图像
      let img = res.fsjData[0].imgs
     
      let imgs=[]
       if (img.length>2){
        imgs[0]=img
        this.setData({
           imgList:imgs
         });   
       }else{
        this.setData({
           imgList: []
         });
       }
      if (res.fsjData[0].mainSignal=='true'){
        this.setData({           
          mainSignal: true,           
        }); 
      }else
      {
        this.setData({
          mainSignal: false,
        }); 
      } 
      if (res.fsjData[0].backSignal == 'true') {
        this.setData({
          backSignal: true,
        });
      } else {
        this.setData({
          backSignal: false,
        });
      } 
      
    }
     this.setData({
      todonum: res.count
    }) 
   
  },
  PickerChange(e) {
    //发射台选择处理
   
    let index0 = e.detail.value
    this.setData({
      index: e.detail.value,
      dtype: this.data.picker[index0].id,
    })
  
    this.fetchpdlist();
  },//end of PickerChange

  DateChange(e) {
    //日期选择处理
    this.setData({
      date: e.detail.value
    })
   
    this.get_log_dat() //调取当日 对应频道数据
  },// end of datechage

  initdate() {
    //日期初始化
    var DATE = util.formatDate(new Date());
    this.setData({
      date: DATE,
    });
  },// end of initdate
  async fetchpdlist() {
    //获取频道信息
   
    let url = 'fsj/listByFstId';
    let data = {
      fstId: this.data.dtype
    }
    let res= await http.post(url,data)
   
    this.setData({
      pdList: res.fsjList,
      totalnum: res.fsjList.length,
      fsjId: res.fsjList[0].id,
      pdname: res.fsjList[0].fstPd       
    });
   
    this.get_log_dat() //调取当日 对应频道数据
  
  },// end of  fetchtype
  async fetchtype() {
    //获取发射机类型及用户信息
    let url = 'fst/listbyuid';
    let data = {
      uid: this.data.uid
    }
    let res= await http.post(url,data)
   
    this.setData({
      picker: res.fstList,
      dtype: res.fstList[0].id,
      // tnametname: res.fstList[0].fstName,        
    });
   
    this.fetchpdlist()
   
  },// end of  fetchtype
  pdSteps() {
    this.setData({
      num: this.data.num == this.data.numList.length - 1 ? 0 : this.data.num + 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    let tname=wx.getStorageSync('tname')
    let uid = wx.getStorageSync('uid')
   let date = options.date.substring(0,10);
   let fst_id=options.fst_id
  
   this.setData({
     tname:tname,
     uid:uid,
     date: date,
     dtype:fst_id

   });
   this.fetchtype()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    //this.initdate()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})